package com.basil.gym.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.basil.gym.constants.RedisConstants;
import com.basil.gym.pojo.dto.AdminLoginDTO;
import com.basil.gym.pojo.dto.AdminResetDTO;
import com.basil.gym.pojo.entity.Admin;
import com.basil.gym.pojo.query.AdminQuery;
import com.basil.gym.service.IAdminService;
import com.basil.gym.util.JwtUtil;
import com.basil.gym.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Basil
 * @since 2025-04-15
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private IAdminService adminService;
    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("/list")
    public Result list(){
        return Result.ok(adminService.list());
    }
    @GetMapping("/selectByPage")
    public Result selectByPage(AdminQuery adminQuery){
        System.out.println(adminQuery);
        IPage<Admin> page = adminService.selectByPage(adminQuery);
        return Result.ok(page);
    }

    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id){
        return Result.ok(adminService.getById(id));
    }

    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable Integer id){
        adminService.removeById(id);
        return Result.ok("删除成功");
    }

    @DeleteMapping("/deleteAll/{ids}")
    public Result deleteAll(@PathVariable Integer[] ids){
        adminService.removeByIds(Arrays.asList(ids));
        return Result.ok("批量删除成功");
    }

    @PutMapping("/update")
    public Result update(@RequestBody Admin admin){
        redisTemplate.opsForSet().add(RedisConstants.UPLOAD_IMAGE_TO_DB, admin.getAvatar());
        adminService.updateById(admin);
        return Result.ok("更新成功");
    }

    @PostMapping("/add")
    public Result add(@RequestBody Admin admin){
        redisTemplate.opsForSet().add(RedisConstants.UPLOAD_IMAGE_TO_DB, admin.getAvatar());
        adminService.save(admin);
        return Result.ok("添加成功");
    }

    @PostMapping("/login")
    public Result login(@RequestBody AdminLoginDTO adminLoginDTO) {
        //首先判断验证码是否正确
        String captcha = (String) redisTemplate.opsForValue().get("captcha:" + adminLoginDTO.getUuid());
        if (ObjectUtils.isEmpty(captcha)) {
            return Result.error("验证码已经失效");
        }
        if (!captcha.equalsIgnoreCase(adminLoginDTO.getCaptcha())) {
            return Result.error("验证码错误");
        }
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", adminLoginDTO.getName());
        queryWrapper.eq("password", adminLoginDTO.getPassword());
        Admin loginAdmin = adminService.getOne(queryWrapper);

        //判断用户名是否存在
        if (ObjectUtils.isEmpty(loginAdmin)) {
            return Result.error("账号不存在");
        }
        //判断用户是否被禁用
        if (loginAdmin.getStatus() == 0) {
            return Result.error("账号被禁用");
        }
        //判断密码是否正确
        if (!loginAdmin.getPassword().equalsIgnoreCase(adminLoginDTO.getPassword())) {
            return Result.error("密码错误");
        }
        //判断密码是否正确  loginUser对象中的password是密文
        /*if (!Md5Util.getMD5String(admin.getPassword()).equalsIgnoreCase(loginAdmin.getPassword())) {
            return Result.error("密码错误");
        }*/

        //登录成功
        Map<String, Object> map = new HashMap<>();
        map.put("id", loginAdmin.getId());
        map.put("name", loginAdmin.getName());
        String token = JwtUtil.createToken(map);
        return Result.ok("登录成功", token);
    }

    @GetMapping("/logout")
    public Result logout() {
        return Result.ok("退出成功");
    }

    @GetMapping("/adminInfo")
    public Result adminInfo(@RequestHeader(name = "Authorization") String token) {
        Map<String, Object> map = JwtUtil.parseToken(token);
        Integer id = (Integer) map.get("id");
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        Admin admin = adminService.getOne(queryWrapper);
        return Result.ok(admin);
    }

    @PutMapping("/resetPassword")
    public Result resetPassword(@RequestBody AdminResetDTO adminResetDTO){
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", adminResetDTO.getId());
        Admin admin = adminService.getOne(queryWrapper);
        System.out.println(adminResetDTO);
        System.out.println(admin);
        if (admin == null || admin.getId() == 1) {
            return Result.error("用户信息错误，不允许修改密码！");
        }
        if (admin.getPassword().equals(adminResetDTO.getOldPassword())) {
            admin.setPassword(adminResetDTO.getNewPassword());
            adminService.updateById(admin);
            return Result.ok("修改成功");
        } else {
            return Result.error("旧密码错误");
        }
    }
}

